package com.wangsir.util;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class MyUtil {
    public static Date strToDate(String str){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return simpleDateFormat.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
    //判断当前登陆的用户是否有某些权限
    public static boolean hasPermission(HttpServletRequest req, HttpServletResponse resp,boolean isAjax,String... roles) throws ServletException, IOException {
        Object role = req.getSession().getAttribute("role");
        List<String> roleList = Arrays.asList(roles);
        //判断当前用户是否为空以及当前登录例表的roleList里面是否含有role
        if(role == null || !roleList.contains(role) ){
            if(!isAjax){
                //如果不是Ajax请求的话就代表用户不是点击访问的，而是通过地址栏输入直接访问了不该访问得页面
                req.getRequestDispatcher("/login.jsp").forward(req,resp);
            }else{
                resp.getWriter().write(ApiResult.json(false,"没有权限"));
            }
            return false;
        }
        return true;
    }
}
